"use strict"
//创建订单,客户端调用,
// 所有订单信息由创建订单的一瞬间决定
exports.create = function () {
    let id  = this.get("id","int")
        ,sid  = this.get("sid","int")
        ,uid  = this.get("uid","string");

    if( !id || !sid || !uid ){
        return this.error("args empty");
    }
    return Promise.resolve().then(()=>{
        if(this.opensdk['payment'] < 1){
            return this.error("payment_closed",this.opensdk['_id']);
        }
        let api = '/order/create';
        let query = {"id":id,"uid":uid,"cyt":this.opensdk['cyt']};
        return this.library("game/request",this.branch,sid,api,query);
    }).then(orderData=>{
        let notify = [this.branch,this.opensdk._id,'order','notify'];
        let service = this.config.get("service");
        if(service && typeof service === 'string'){
            notify.unshift(service);
        }
        notify.unshift('');
        let api =notify.join('/');
        let url = [this.req.protocol ,"://",this.req.hostname,api].join('');
        return this.library.call(this,"opensdk/handle","orderCreate",orderData,url);
    })
};


//订单回调,orderNotify:{"attach","orderid"}
exports.notify = function () {
    return Promise.resolve(1).then(()=>{
        return this.library.call(this,"opensdk/handle","orderNotify");
    }).then(data=>{
        if(!data['attach']){
            return this.error("order_attach_error",data['attach']);
        }
        let s = data['attach'].indexOf("|") >0 ? "|" :"z";
        let arr = data['attach'].split(s);
        let uid = arr[0],sid = parseInt(arr[1]),id = arr[2];
        if(!uid || !sid || !id){
            return this.error("order_attach_error",data['attach']);
        }
        let query = {"id":id,"uid":uid,"cyt":this.opensdk['cyt'],"sdk":this.opensdk._id,"amount":data['amount']||0,"orderid":data['orderid'] };
        return this.library("game/notify",this.branch,sid,query);
    }).then(ret=>{
        return this.library.call(this,"opensdk/handle","orderResult",null,ret);
    }).catch(err=>{
        return this.library.call(this,"opensdk/handle","orderResult",err);
    })
}

//智能处理create和notify，根据里面的参数或者调用方式POST还是GET来自动路由
exports.autoP = function () {
    return this.library.call(this,"opensdk/handle","autoP");
}






